package com.joseph.websocket.transfer;

import com.joseph.websocket.component.NodeManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TransferMessageHandler extends SimpleChannelInboundHandler<String> {

    private static final Logger LOGGER = LoggerFactory.getLogger(TransferMessageHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("node connect {}", ctx.channel().remoteAddress().toString());
        NodeManager.add(ctx.channel().remoteAddress().toString(), ctx.channel());
        super.channelActive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {

            }
        });
        LOGGER.info("msg from node {}", msg);
        Channel channel = NodeManager.get(ctx.channel().remoteAddress().toString());
        channel.writeAndFlush(msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("node disconnect {}", ctx.channel().remoteAddress().toString());
        NodeManager.remove(ctx.channel().remoteAddress().toString());
        super.channelInactive(ctx);
    }

    public static void main(String[] args) {
        assert false;
    }
}
